/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.auth.wechat.miniapp.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

/**
 * <b>(WechatMiniappService)</b>
 * 微信小程序相关功能
 *
 * @author LiHai
 * @version 1.0.0
 * @since 2023/7/19
 */
@Slf4j
@Component
public class WechatMiniappService {
    @Inject
    WxMaService wxMaService;

    public WxMaUserInfo info(String appId, String sessionKey, String encryptedData, String iv) {
        if (!wxMaService.switchover(appId)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appId));
        }

        // 解密客户信息
        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        WxMaConfigHolder.remove();//清理ThreadLocal
        return userInfo;
    }

    public WxMaJscode2SessionResult login(String appId, String code) {
        if (!wxMaService.switchover(appId)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appId));
        }

        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            log.info(session.getSessionKey());
            log.info(session.getOpenid());
            // TODO 可以增加自己的逻辑，关联业务相关数据
            return session;
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
        return null;
    }

    public WxMaPhoneNumberInfo phone(String appId, String sessionKey, String encryptedData, String ivStr) {
        if (!wxMaService.switchover(appId)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appId));
        }

        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, ivStr);
        WxMaConfigHolder.remove();//清理ThreadLocal
        return phoneNoInfo;
    }
}